package com.project.mq.mqclient;

import com.project.mq.common.*;
import lombok.Data;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Data
public class Connection {
    private Socket socket = null;
    private InputStream inputStream;
    private OutputStream outputStream;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    // 记录当前 Connection 包含的 Channel
    private ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>();
    // 执行消费消息回调的线程池
    private ExecutorService callbackPool = Executors.newFixedThreadPool(4);

    public Connection(String host,int port) throws IOException {
        socket = new Socket(host, port);
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        dataInputStream = new DataInputStream(inputStream);
        dataOutputStream = new DataOutputStream(outputStream);

        // 创建一个扫描线程，由这个线程负责不停的从 socket 中读取响应数据。把这个响应数据再交给对应的 channel 负责处理。
        Thread t = new Thread(() -> {
            try {
                while (!socket.isClosed()) {
                    Response response = readResponse();
                    dispatchResponse(response);
                }
            } catch (SocketException e) {
                // 连接断开，忽略该异常。
                System.out.println("[Connection] 连接断开!");
            } catch (IOException | ClassNotFoundException | MqException e) {
                System.out.println("[Connection] 连接出现异常!");
                e.printStackTrace();
            }
        });
        t.start();
    }

    // 使用这个方法来分别处理，当前的响应是一个针对控制请求的响应，还是服务器推送的消息。
    private void dispatchResponse(Response response) throws IOException, ClassNotFoundException, MqException {
        if (response.getType() == 0xc) {
            //服务器推送的消息
            // 1. 解析到服务器返回的订阅数据
            SubscribeReturns subScribeReturns = (SubscribeReturns) BinaryTool.fromBytes(response.getPayload());

            //根据channalId找到相对应的对象
            // 2. 获取到 channel
            Channel channel = channelMap.get(subScribeReturns.getChannelId());
            if (channel == null) {
                throw new MqException("该消息对应的 channel 不存在! channelId=" + subScribeReturns.getChannelId());
            }

            // 3. 执行 channel 中对应的回调.
            callbackPool.submit(() -> {
                try {
                    channel.getConsumer().handleDelivery(subScribeReturns.getConsumerTag(),
                            subScribeReturns.getBasicProperties(), subScribeReturns.getBody());
                } catch (MqException | IOException e) {
                    e.printStackTrace();
                }
            });
        } else {
            // 针对控制请求的响应
            // 1. 拿到服务器返回的控制消息
            BaseReturns baseReturns = (BaseReturns) BinaryTool.fromBytes(response.getPayload());
            // System.out.printf("[Connection] 收到响应: type=0x%x, channelId=%s, ok=%b\n", response.getType(),
            //         baseReturns.getChannelId(), baseReturns.isOk());

            // 2. 找到对应 Channel
            //把这个就结果放到对应的channal的hash表中
            Channel channel = channelMap.get(baseReturns.getChannelId());
            if (channel == null) {
                // 这个是小问题，不要抛异常
                System.out.println("[Connection] channel 不存在! channelId=" + baseReturns.getChannelId());
                return;
            }

            // 3. 把响应放到对应的 Channel 的 map 中.
            channel.putReturns(baseReturns);
        }
    }

    //发送请求
    public void writeRequest(Request request) throws IOException {
        dataOutputStream.writeInt(request.getType());
        dataOutputStream.writeInt(request.getLength());
        dataOutputStream.write(request.getPayload());
        dataOutputStream.flush();
        System.out.println("[Connection] 发送请求! type=" + request.getType() + ", length=" + request.getLength());
    }
    // 读取响应应该在另外一个单独的线程中完成.
    public Response readResponse() throws IOException {
        Response response = new Response();
        response.setType(dataInputStream.readInt());
        response.setLength(dataInputStream.readInt());
        byte[] payload = new byte[response.getLength()];

        int n = dataInputStream.read(payload);
        if (n != response.getLength()) {
            throw new IOException("读取到的响应数据不完整!");
        }
        response.setPayload(payload);
        System.out.println("[Connection] 收到响应! type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }

    //通过这个方法,在Connection中能够创建出一个Channel
    public Channel createChannel() throws IOException {
        // 使用 UUID 生成 channelId，以 C- 开头
        String channelId = "C-" + UUID.randomUUID().toString();
        Channel channel = new Channel(channelId, this);
        // 这里需要先把 channel 键值对放到 Map 中. 否则后续 createChannel 的阻塞等待就等不到结果了
        channelMap.put(channelId, channel);
        // 同时也需要把 "创建 channel" 的这个消息也告诉服务器。
        boolean ok = channel.createChannel();
        if (!ok) {
            // 服务器返回创建 channel 失败!
            // 把 channelId 删除掉即可
            channelMap.remove(channelId);
            return null;
        }
        return channel;
    }

    //关闭 Connection
    //释放上述资源
    public void close() {
        try {
            callbackPool.shutdown();
            channelMap = null;
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}